import base64
import json
import pickle

from django.http import JsonResponse
from django.views import View
from django_redis import get_redis_connection

from apps.goods.models import SKU


class CartView(View):

    def post(self, request):
        # 1.接受参数
        json_dict = json.loads(request.body)
        sku_id = json_dict.get('sku_id')
        count = json_dict.get('count')
        selected = json_dict.get('selected', True)
        # 2.检验参数
        # 检验参数是否缺失
        if not all([sku_id, count]):
            return JsonResponse({'code': 400, 'errmsg': '参数缺失'})
        # 判断对应的sku是否存在
        try:
            SKU.objects.get(id=sku_id)
        except SKU.DoesNotExist:
            return JsonResponse({'code': 400, 'errmsg': 'sku不存在'})
        # 判断count是否为数字
        try:
            count = int(count)
        except Exception:
            return JsonResponse({'code': 400, 'errmsg': '参数有误'})
        # 判断selected是否为布尔值
        if selected:
            if not isinstance(selected, bool):
                return JsonResponse({'code': 400, 'errmsg': '参数selected有错误'})

        # 3.判断用户是否登录
        user = request.user
        if user.is_authenticated:
            # 连接redis
            redis_cli = get_redis_connection('carts')
            pl = redis_cli.pipeline()
            pl.hincrby('carts_%s' % user.id, sku_id, count)
            # 增加选中状态
            if selected:
                pl.sadd('selected_%s' % user.id, sku_id)
            pl.execute()
            return JsonResponse({'code': 0, 'errmsg': '添加购物车成功'})
        else:
            cart_str = request.COOKIES.get('carts')
            if cart_str:
                cart_dict = pickle.loads(base64.b64decode(cart_str.encode()))
            else:
                cart_dict = {}

            if sku_id in cart_dict:
                origin_count = cart_dict[sku_id]['count']
                count += origin_count
            cart_dict[sku_id] = {
                'count': count,
                'selected': selected
            }
            cookie_cart_str = base64.b64encode(pickle.dumps(cart_dict)).decode()
            response = JsonResponse({'code': 0, 'errmsg': '添加购物车成功'})
            response.set_cookie('carts', cookie_cart_str, max_age=7 * 24 * 3600)
            return response

    def get(self, request):
        # 1.判断是否登录
        user = request.user
        # 检查是否登录
        if user.is_authenticated:
            # 从redis获取数据
            redis_cli = get_redis_connection('carts')
            cart_data = redis_cli.hgetall('carts_%s' % user.id)

            cart_selected = redis_cli.smembers('selected_%s' % user.id)
            # 将获取的数据转换为字典
            cart_dict = {}
            for sku_id, count in cart_data.items():
                cart_dict[int(sku_id)] = {
                    'count': int(count),
                    'selected': sku_id in cart_selected
                }
        else:
            # 从cookie中获取数据
            cart_str = request.COOKIES.get('carts')
            if cart_str:
                cart_dict = pickle.loads(base64.b64decode(cart_str.encode()))
            else:
                cart_dict = {}

        # 将获取的数据构造为购物车的渲染数据
        sku_ids = cart_dict.keys()
        skus = SKU.objects.filter(id__in=sku_ids)
        cart_skus = []
        for sku in skus:
            cart_skus.append({
                'id': sku.id,
                'name': sku.name,
                'count': cart_dict.get(sku.id).get('count'),
                'selected': str(cart_dict.get(sku.id).get('selected')),  # 将True，转'True'，方便json解析
                'default_image_url': sku.default_image.url,
                'price': str(sku.price),  # 从Decimal('10.2')中取出'10.2'，方便json解析
                'amount': str(sku.price * cart_dict.get(sku.id).get('count')),
            })
        return JsonResponse({'code': 0, 'errmsg': 'ok', 'cart_skus': cart_skus})

    def put(self, request):
        # 1.接收数据
        data_dict = json.loads(request.body)
        sku_id = data_dict.get('sku_id')
        count = data_dict.get('count')
        selected = data_dict.get('selected', True)
        # 2.校验参数
        if not all([sku_id, count]):
            return http.HttpResponseBadRequest('缺少必传参数')
            # 判断sku_id是否存在
        try:
            sku = SKU.objects.get(id=sku_id)
        except SKU.DoesNotExist:
            return http.HttpResponseBadRequest('商品sku_id不存在')
            # 判断count是否为数字
        try:
            count = int(count)
        except Exception:
            return http.HttpResponseBadRequest('参数count有误')

        # 3.判断用户是否登录
        user = request.user
        if user.is_authenticated:
            # 连接redis
            redis_cli = get_redis_connection('carts')
            pl = redis_cli.pipeline()
            pl.hset('carts_%s' % user.id, sku_id, count)
            if selected:
                pl.sadd('selected_%s' % user.id, sku_id)
            else:
                pl.srem('selected_%s' % user.id, sku_id)
            pl.execute()
            # 创建响应对象
            cart_sku = {
                'id': sku_id,
                'count': count,
                'selected': selected,
                'name': sku.name,
                'default_image_url': sku.default_image.url,
                'price': sku.price,
                'amount': sku.price * count,
            }
            return JsonResponse({'code': 0, 'errmsg': 'ok', 'cart_sku': cart_sku})
        else:
            # 获取cookie数据
            cart_data = request.COOKIES.get('carts')
            if cart_data:
                cart_dict = pickle.loads(base64.b64decode(cart_data.encode()))
            else:
                cart_dict = {}
            cart_dict[sku_id] = {
                'count': count,
                'selected': selected
            }
            cart_cookie = base64.b64encode(pickle.dumps(cart_dict)).decode()
            # 创建响应对象
            cart_sku = {
                'id': sku_id,
                'count': count,
                'selected': selected,
                'name': sku.name,
                'default_image_url': sku.default_image.url,
                'price': sku.price,
                'amount': sku.price * count,
            }
            response = JsonResponse({'code': 0, 'errmsg': 'ok', 'cart_sku': cart_sku})
            response.set_cookie('carts', cart_cookie, max_age=7 * 24 * 3600)
            return response

    def delete(self, requset):
        # 获取数据
        data_dict = json.loads(requset.body)
        sku_id = data_dict.get('sku_id')
        # 校验数据
        # 判断sku是否存在
        try:
            sku = SKU.objects.get(id=sku_id)
        except SKU.DoesNotExist:
            return JsonResponse({'code': 400, 'errmsg': 'sku不存在'})
        # 判断用户啊是否登录
        user = requset.user
        if user.is_authenticated:
            # 连接redis
            redis_cli = get_redis_connection('carts')
            pl = redis_cli.pipeline()
            pl.hdel('carts_%s' % user.id, sku_id)
            pl.srem('selected_%s' % user.id, sku_id)
            pl.execute()
            return JsonResponse({'code': 0, 'errmsg': '删除购物车成功'})
        else:
            # 获取cookie信息
            cart_data = requset.COOKIES.get('carts')
            if cart_data:
                cart_dict = pickle.loads(base64.b64decode(cart_data.encode()))
            else:
                cart_dict = {}
            # 创建响应对象
            response = JsonResponse({'code': 0, 'errmsg': '删除购物车成功'})
            if sku_id in cart_dict:
                del cart_dict[sku_id]
                cart_cookie = base64.b64encode(pickle.dumps(cart_dict)).decode()
                response.set_cookie('carts', cart_cookie, max_age=7 * 24 * 3600)
            return response


class CartsSelectionView(View):
    def put(self, request):
        # 1.获取数据
        data_dict = json.loads(request.body)
        selected = data_dict.get('selected')
        # 检验数据
        if selected:
            if not isinstance(selected, bool):
                return JsonResponse({'code': 0, 'errmsg': 'selected有误'})
        # 检查用户是否登录
        user = request.user
        if user.is_authenticated:
            redis_cli = get_redis_connection('carts')
            cart_sku = redis_cli.hgetall('carts_%s' % user.id)
            sku_ids = cart_sku.keys()
            if selected:
                redis_cli.sadd('selected_%s' % user.id, *sku_ids)
            else:
                redis_cli.srem('selected_%s' % user.id, *sku_ids)
            return JsonResponse({'code': 0, 'errmsg': '全选购物车成功'})
        else:
            cart_data = request.COOKIES.get('carts')
            response = JsonResponse({'code': 0, 'errmsg': '全选购物车成功'})
            if cart_data is not None:
                cart_dict = pickle.loads(base64.b64decode(cart_data.encode()))
                for sku_id in cart_dict:
                    cart_dict[sku_id]['selected'] = selected
                cart_cookie = base64.b64encode(pickle.dumps(cart_dict)).decode()
                response.set_cookie('carts', cart_cookie, max_age=7 * 24 * 3600)
            return response


class CartsSimpleView(View):
    def get(self, request):
        # 判断用户是否登录
        user = request.user
        if user.is_authenticated:
            # 获取redis数据
            redis_cli = get_redis_connection('carts')
            redis_cart = redis_cli.hgetall('carts_%s' % user.id)
            redis_selected = redis_cli.smembers('selected_%s' % user.id)
            cart_dict = {}
            for sku_id, count in redis_cart.items():
                cart_dict[int(sku_id)] = {
                    'count': int(count),
                    'selected': sku_id in redis_selected
                }
        else:
            # 获取cookie数据
            cart_str = request.COOKIES.get('carts')
            if cart_str:
                cart_dict = pickle.loads(base64.b64decode(cart_str.encode()))
            else:
                cart_dict = {}

        cart_skus = []
        sku_ids = cart_dict.keys()
        skus = SKU.objects.filter(id__in=sku_ids)
        for sku in skus:
            cart_skus.append({
                'id': sku.id,
                'name': sku.name,
                'count': cart_dict.get(sku.id).get('count'),
                'default_image_url': sku.default_image.url
            })
        return JsonResponse({'code': 0, 'errmsg': 'OK', 'cart_skus': cart_skus})